<template>
  <div class="recruiter-list">
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="Home" :replace="true">首页</el-breadcrumb-item>
        <el-breadcrumb-item>招聘专员信息列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-form :inline="true" :model="recruiterQueryForm" ref="recruiterQueryFormRef" :rules="rules">
      <el-form-item label="企业名称" prop="enterpriseName">
        <el-input v-model="recruiterQueryForm.enterpriseName" placeholder="请选择企业名称" readonly="readonly">
          <template #suffix>
            <el-icon @click="findEnterprise"><Search/></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="recruiterQueryForm.username" placeholder="请输入用户名" maxlength="64"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="recruiterQueryForm.name" placeholder="请输入姓名" maxlength="64"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onAdd">新增</el-button>
        <el-button type="primary" @click="onExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="state.tableData"
      border
      v-loading="state.loading"
      size="small"
      header-cell-class-name="table-header-cell-font"
      cell-class-name="table-cell-font">
      <el-table-column prop="enterpriseName" label="企业名称"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>
      <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template v-slot="{ row }">
          <el-button @click.prevent="editRow(row.id)" type="primary">编辑</el-button>
          <el-button @click.prevent="delRow(row.id)" type="danger" plain>删除</el-button>
          <el-button @click.prevent="detailRow(row.id)" type="primary" plain>详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination
        @current-change="changePage"
        :current-page="state.currentPage"
        :page-sizes="state.pageSizes"
        :page-size="state.pageSize"
        background
        layout="total, prev, pager, next, jumper"
        :total="state.total">
      </el-pagination>
    </div>
    <el-dialog v-model="enterpriseSelectorVisible" v-if="enterpriseSelectorVisible" title="企业信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <enterprise-selector @enterprise-selected-event="handleEnterpriseSelectedEvent">
      </enterprise-selector>
    </el-dialog>
    <el-dialog v-model="recruiterAddVisible" v-if="recruiterAddVisible" :title="recruiterAddTitle" :top="dialogTop" :width="dialogWidth">
      <recruiter-add :id="selectedRecruiterId" @close-recruiter-add-event="handleCloseRecruiterAddEvent" @reset-recruiter-add-event="handleResetRecruiterAddEvent">
      </recruiter-add>
    </el-dialog>
    <el-dialog v-model="recruiterViewVisible" v-if="recruiterViewVisible" title="招聘专员信息详情" :top="dialogTop" :width="dialogWidth">
      <recruiter-view :id="selectedRecruiterId" @close-recruiter-view-event="handleCloseRecruiterViewEvent">
      </recruiter-view>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, inject, toRefs} from 'vue';
import recruiterApi from '@/api/recruiterApi'
import type {RecruiterQueryForm} from "@/types/req/recruiterQueryForm";
import type {Recruiter} from "@/types/resp/recruiter";
import {ElMessage, ElMessageBox, type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import EnterpriseSelector from "@/views/enterprise/EnterpriseSelector.vue";
import RecruiterAdd from "@/views/recruiter/RecruiterAdd.vue"
import RecruiterView from "@/views/recruiter/RecruiterView.vue"
import { exportToExcel } from '@/composables/exportUtil.ts'


const recruiterQueryFormRef = ref<FormInstance | null>(null);
const recruiterQueryForm = reactive<RecruiterQueryForm>({
  enterpriseId: 0,
  enterpriseName: '',
  username: '',
  name: '',
})

const state = reactive({
  loading: false,
  tableData: [] as Recruiter[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})
const selectedRecruiterId = ref<number>(0)
const enterpriseSelectorVisible = ref<boolean>(false)
const recruiterAddVisible = ref<boolean>(false)
const recruiterViewVisible = ref<boolean>(false)
const recruiterAddTitle = ref<string>('')
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

onMounted(() => {
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<Recruiter>> = await recruiterApi.find(recruiterQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
      const page: Page<Recruiter> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (recruiterQueryFormRef.value) {
    recruiterQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const onAdd = () => {
  selectedRecruiterId.value = 0
  recruiterAddVisible.value = true
  recruiterAddTitle.value = '招聘专员信息新增'
}
const editRow = (id: number) => {
  selectedRecruiterId.value = id
  recruiterAddVisible.value = true
  recruiterAddTitle.value = '招聘专员信息编辑'
}
const delRow = (id: number) => {
  if (!id) {
    return
  }
  ElMessageBox.confirm(
    '确定要删除吗?',
    '删除提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    recruiterApi.del(id)
      .then((resp) => {
        if (resp && resp.code === 1) {
          ElMessage.success('删除成功!')
          onSearch()
        } else {
          ElMessage.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
        }
      })
      .catch(error => {
        console.error('操作失败:', error)
      })
  }).catch(() => {})
}
const detailRow = (id:number) => {
  selectedRecruiterId.value = id
  recruiterViewVisible.value = true
}

const findEnterprise = () => {
  enterpriseSelectorVisible.value = true
}

const handleEnterpriseSelectedEvent = (selectedEnterprise: any) => {
  enterpriseSelectorVisible.value = false
  if (selectedEnterprise && 'enterpriseId' in selectedEnterprise && recruiterQueryForm.enterpriseId !== selectedEnterprise['enterpriseId']) {
    recruiterQueryForm.enterpriseId = selectedEnterprise['enterpriseId']
    recruiterQueryForm.enterpriseName = selectedEnterprise['enterpriseName']
  }
}

const handleCloseRecruiterViewEvent = () => {
  recruiterViewVisible.value = false
}

const handleResetRecruiterAddEvent = () => {
  recruiterAddTitle.value = '招聘专员信息新增'
}

const handleCloseRecruiterAddEvent = (params: { search?: boolean } | undefined) => {
  if (params && params.search) {
    onSearch()
  }
  recruiterAddVisible.value = false
}

const onExport = () => {
  const headers = ['企业名称','用户名','姓名','密码','联系电话','邮箱']
  recruiterApi.find(recruiterQueryForm).then(data => {
    if (!data || !data.data || data.data.list.length < 1) {
      ElMessage.error('无数据导出')
      return
    }
    const exportData = []
    for (const d of data.data.list) {
      exportData.push([d.enterpriseName,d.username,d.name,d.password,d.contactPhone,d.email])
    }
    exportToExcel(headers, exportData)
  })
}
</script>

<style lang="scss">
</style>